<template>
  <div>
    <!-- 主对话框 -->
    <el-dialog
      :title="selectMode ? 'PI账户信息选择' : 'PI账户信息管理'"
      :visible.sync="dialogMainVisible"
      width="90%"
      :before-close="handleMainClose"
      class="pi-account-dialog"
    >
      <el-container>
        <el-header style="margin-top: 10px;height: auto;">
          <el-row>
            <el-input
              v-model="kwInput"
              placeholder="输入账户名称、公司名称等关键字进行筛选"
              class="input-with-select"
              clearable
              style="max-width: 600px"
              @keyup.native.enter="handleSearch"
            >
              <el-button slot="append" icon="el-icon-search" :loading="listLoading" @click="handleSearch">搜索</el-button>
            </el-input>
            <el-button
              v-if="!selectMode"
              type="primary"
              class="el-icon-plus add-btn"
              :disabled="listLoading"
              @click="handleAction('create', '新建PI账户信息')"
            >新建PI账户信息
            </el-button>
          </el-row>
        </el-header>
        <el-main>
          <el-table
            v-loading="listLoading"
            :data="data"
            border
            fit
            highlight-current-row
            style="width: 100%"
            @cell-mouse-enter="(m) => m.active=true"
            @cell-mouse-leave="(m) => m.active=false"
            @sort-change="handleSort"
          >
            <el-table-column align="center" width="80" prop="id" label="ID" sortable="custom" />
            <el-table-column prop="name" label="账户昵称" width="200" sortable="custom" />
            <el-table-column prop="pi_company_name" label="公司名称" width="200" />
            <el-table-column prop="pi_email" label="邮箱" width="180" />
            <el-table-column prop="pi_phone" label="电话" width="150" />
            <el-table-column prop="pi_account_holder_name" label="账户持有人" width="150" />
            <el-table-column prop="pi_account_number" label="账户号码" width="150" />
            <el-table-column prop="pi_bank_name" label="银行名称" width="150" />
            <el-table-column prop="pi_swift_code" label="SWIFT代码" width="120" />
            <el-table-column align="center" fixed="right" label="操作" :width="selectMode ? '120' : '200'">
              <template slot-scope="scope">
                <el-button v-if="selectMode" size="mini" type="primary" @click="handleSelect(scope.row)">选择</el-button>
                <template v-else>
                  <el-button size="mini" type="success" @click="handleAction('edit', scope.row)">修改</el-button>
                  <el-button size="mini" type="danger" @click="handleAction('delete', scope.row)">删除</el-button>
                </template>
              </template>
            </el-table-column>
          </el-table>
          <el-pagination
            v-show="total>0"
            background
            :current-page="listQuery.page"
            :page-sizes="[10, 20, 50, 100]"
            :page-size="listQuery.pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handlePageChange"
          />
        </el-main>
      </el-container>

      <!-- 新增/编辑对话框 -->
      <el-dialog v-if="!selectMode" :title="title" :visible.sync="dialogVisible" :width="width" append-to-body @close="resetTemp">
        <el-form :model="temp" label-width="120px" class="mt-form">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="账户昵称" prop="name">
                <el-input v-model="temp.name" placeholder="请输入账户名称" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="公司名称" prop="pi_company_name">
                <el-input v-model="temp.pi_company_name" placeholder="请输入公司名称" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="邮箱" prop="pi_email">
                <el-input v-model="temp.pi_email" placeholder="请输入邮箱" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="电话" prop="pi_phone">
                <el-input v-model="temp.pi_phone" placeholder="请输入电话" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-form-item label="网站" prop="pi_website">
            <el-input v-model="temp.pi_website" placeholder="请输入网站地址" />
          </el-form-item>
          <el-form-item label="PI地址" prop="pi_address">
            <el-input v-model="temp.pi_address" type="textarea" :rows="3" placeholder="请输入PI地址" />
          </el-form-item>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="账户持有人" prop="pi_account_holder_name">
                <el-input v-model="temp.pi_account_holder_name" placeholder="请输入账户持有人姓名" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="账户号码" prop="pi_account_number">
                <el-input v-model="temp.pi_account_number" placeholder="请输入账户号码" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-form-item label="银行名称" prop="pi_bank_name">
            <el-input v-model="temp.pi_bank_name" placeholder="请输入银行名称" />
          </el-form-item>
          <el-form-item label="银行地址" prop="pi_bak_address">
            <el-input v-model="temp.pi_bak_address" type="textarea" :rows="3" placeholder="请输入银行地址" />
          </el-form-item>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="ACH路由号" prop="pi_ach_routing_number">
                <el-input v-model="temp.pi_ach_routing_number" placeholder="请输入ACH路由号码" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="电汇号码" prop="pi_wire_transfer_number">
                <el-input v-model="temp.pi_wire_transfer_number" placeholder="请输入电汇号码" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-form-item label="SWIFT代码" prop="pi_swift_code">
            <el-input v-model="temp.pi_swift_code" placeholder="请输入SWIFT代码" />
          </el-form-item>
          <el-form-item label="公司Logo" prop="company_logo">
            <div class="logo-input-container">
              <el-input v-model="temp.company_logo" placeholder="请输入公司Logo图片URL" style="margin-bottom: 10px;" />
              <div v-if="temp.company_logo" class="logo-preview">
                <img :src="temp.company_logo" alt="公司Logo" class="logo-image" @error="handleLogoError">
                <el-button type="text" size="mini" class="clear-logo-btn" @click="clearLogo">
                  <i class="el-icon-delete" /> 清除
                </el-button>
              </div>
            </div>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirm">确定</el-button>
        </div>
      </el-dialog>

      <!-- 删除确认对话框 -->
      <el-dialog v-if="!selectMode" :title="title" :visible.sync="deleteDialogVisible" :width="'30%'" append-to-body>
        <span>{{ deleteMessage }}</span>
        <div slot="footer" class="dialog-footer">
          <el-button @click="deleteDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmDelete">确定</el-button>
        </div>
      </el-dialog>
    </el-dialog>
  </div>
</template>

<script>
import { Get, Post, Put, Delete } from '@/api/crm/crmpiaccountinfo'
import qs from 'qs'

const orderMapper = {
  'ascending': 0,
  'descending': 1,
  'null': ''
}

export default {
  name: 'Crmpiaccountinfo',
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    selectMode: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      data: [],
      listLoading: false,
      kwInput: '',
      order_by: '',
      order_desc: '',
      // pagination
      listQuery: {
        page: 1,
        pageSize: 10
      },
      total: 0,
      action: null,
      dialogVisible: false,
      deleteDialogVisible: false,
      title: '',
      width: '60%',
      deleteMessage: '',
      temp: {
        name: '',
        pi_address: '',
        pi_email: '',
        pi_phone: '',
        pi_website: '',
        pi_account_holder_name: '',
        pi_account_number: '',
        pi_bank_name: '',
        pi_bak_address: '',
        pi_ach_routing_number: '',
        pi_wire_transfer_number: '',
        pi_swift_code: '',
        pi_company_name: '',
        company_logo: ''
      }
    }
  },
  computed: {
    dialogMainVisible: {
      get() {
        return this.visible
      },
      set(val) {
        this.$emit('update:visible', val)
      }
    }
  },
  watch: {
    visible(newVal) {
      if (newVal) {
        this.getList()
      }
    }
  },
  methods: {
    handleMainClose() {
      this.$emit('close')
    },
    handleSelect(row) {
      this.$emit('select', row)
      this.handleMainClose()
    },
    resetTemp() {
      this.temp = {
        name: '',
        pi_address: '',
        pi_email: '',
        pi_phone: '',
        pi_website: '',
        pi_account_holder_name: '',
        pi_account_number: '',
        pi_bank_name: '',
        pi_bak_address: '',
        pi_ach_routing_number: '',
        pi_wire_transfer_number: '',
        pi_swift_code: '',
        pi_company_name: '',
        company_logo: ''
      }
    },
    getList() {
      this.listLoading = true
      Get(null, qs.stringify({
        kw: this.kwInput,
        pagesize: this.listQuery.pageSize,
        page: this.listQuery.page,
        order_by: this.order_by,
        order_desc: this.order_desc
      }))
        .then(response => {
          this.scrollTop()
          this.data = response.data.data
          this.listLoading = false
          this.total = response.data.total
        }).catch(err => {
          console.log(err)
          this.listLoading = false
        })
    },
    handleAction(action, row) {
      this.action = action
      switch (action) {
        case 'create':
          this.resetTemp()
          this.width = '60%'
          this.title = '新建PI账户信息'
          this.dialogVisible = true
          break
        case 'delete':
          this.deleteMessage = `确认要删除账户：${row.name}?`
          this.temp = Object.assign({}, row)
          this.deleteDialogVisible = true
          break
        case 'edit':
          this.width = '60%'
          this.title = `修改PI账户信息：${row.name}`
          this.temp.id = row.id
          Object.keys(this.temp).forEach(key => {
            if (row[key] !== undefined) this.temp[key] = row[key]
          })
          this.dialogVisible = true
          break
      }
    },
    confirm() {
      const _data = this.temp
      switch (this.action) {
        case 'create':
          Post(_data).then(response => {
            this.dialogVisible = false
            this.getList()
            this.notify('添加成功')
          }).catch(err => {
            console.log(err)
          })
          break
        case 'edit':
          Put(_data.id, _data).then((response) => {
            this.dialogVisible = false
            this.getList()
            this.notify('更新成功')
          }).catch(err => {
            console.log(err)
          })
          break
      }
    },
    confirmDelete() {
      Delete(this.temp.id).then((response) => {
        this.deleteDialogVisible = false
        this.getList()
        this.notify('删除成功')
      }).catch(err => {
        console.log(err)
      })
    },
    notify(message, duration) {
      this.$notify({
        title: '成功',
        message: message,
        type: 'success',
        duration: duration || 2000
      })
    },
    // pageSize 改变后触发 table 更新
    handleSizeChange(val) {
      this.listQuery.pageSize = val
      this.getList()
    },
    // page 改变后触发 table 更新
    handlePageChange(val) {
      this.listQuery.page = val
      this.getList()
    },
    // 点击搜索
    handleSearch() {
      this.listQuery.page = 1
      this.getList()
    },
    handleSort(v) {
      this.order_by = v.prop
      this.order_desc = orderMapper[v.order]
      this.getList()
    },
    scrollTop() {
      window.scrollTo(0, 0)
    },
    handleLogoError() {
      // Handle logo error
    },
    clearLogo() {
      this.temp.company_logo = ''
    }
  }
}
</script>

<style scoped>
.input-with-select {
  width: calc(100% - 200px);
}

.add-btn {
  float: right;
  margin-right: 20px;
  width: 180px
}

.mt-form >>> .el-select {
  width: 100%;
}

.mt-form >>> .el-input__inner {
  width: 100%;
}

.pi-account-dialog >>> .el-dialog__body {
  padding: 10px 20px;
}

.pi-account-dialog >>> .el-header {
  padding: 0;
}

.pi-account-dialog >>> .el-main {
  padding: 10px 0;
}

.logo-input-container {
  position: relative;
}

.logo-preview {
  position: relative;
  margin-top: 10px;
  padding: 10px;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  background-color: #fafafa;
  display: flex;
  align-items: center;
}

.logo-image {
  width: 80px;
  height: 80px;
  object-fit: contain;
  border: 1px solid #ddd;
  border-radius: 4px;
  margin-right: 10px;
}

.clear-logo-btn {
  color: #f56c6c;
}
</style>
